package common.gateway.demo04.filter;

import common.gateway.demo04.filter.entity.AddResponseHeaderData;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Arrays;
import java.util.List;

/**
 * 添加 response header 的filter factory
 *
 * @author lihh
 */
@Component
public class AddResponseHeadersGatewayFilterFactory extends AbstractGatewayFilterFactory<AddResponseHeaderData> {
  
  public AddResponseHeadersGatewayFilterFactory() {
    super(AddResponseHeaderData.class);
  }
  
  @Override
  public List<String> shortcutFieldOrder() {
    return Arrays.asList("key", "value");
  }
  
  @Override
  public GatewayFilter apply(AddResponseHeaderData config) {
    // 这里 实例化 GatewayFilter
    return new GatewayFilter() {
      @Override
      public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        exchange.getResponse().getHeaders().add(config.getKey(), config.getValue());
        return chain.filter(exchange);
      }
    };
  }
}
